﻿/**************************************************************
*作者：Leon
*创建时间：2022/4/8 8:34:46
**************************************************************/
using System.Runtime.CompilerServices;
using Microsoft.Toolkit.Mvvm.ComponentModel;

namespace Lad.DrawProject.Controls;

public abstract class ObservableRecipientAction : ObservableRecipient
{
    protected IDiagramServiceProvider Service { get { return DiagramServicesProvider.Instance; } }
    protected ActionManager ActionManager => Service.ActionManager;
    private readonly Dictionary<string, object> _oldDic = new();
    private const int Capacity = 30;
    public void SetOldValue(object value!!, string propertyName, string? guid = null)
    {
        if (_oldDic.Count > Capacity)
            RemoveOldValue(propertyName, guid);

        _oldDic[propertyName + guid ?? string.Empty] = value;
    }
    public void SetOldValue(List<(object Value, string Key)> values)
    {
        foreach (var (Value, Key) in values)
            _oldDic[Key] = Value;
    }
    public T? GetOldValue<T>(string propertyName, string? guid = null)
    {
        return _oldDic.TryGetValue(propertyName + guid ?? string.Empty, out var value)
            ?(T)value
            : default;
    }
    private void RemoveOldValue(string propertyName, string? guid = null)
    {
        if (_oldDic.ContainsKey(propertyName + guid ?? string.Empty))
            _oldDic.Remove(propertyName + guid ?? string.Empty);
    }

    public void DoAction(Action action, Action unDoAction)
    {
        ActionManager.DoAction(action, unDoAction);
    }
    public void DoAction<T>(object sender, T? oldValue, T? newValue, [CallerMemberName] string? propertyName = default)
    {
        ActionManager.DoAction(new PropertyChangedAction<T>(sender, oldValue, newValue, propertyName));
    }

    public void AddAction(Action action, Action unDoAction)
    {
        ActionManager.AddAction(action,unDoAction);
    }
    public void AddAction<T>(object sender, T? oldValue, T? newValue, [CallerMemberName] string? propertyName = default)
    {
        ActionManager.AddAction(new PropertyChangedAction<T>(sender, oldValue, newValue, propertyName));
    }
    public void AddActions(ActionGroup actionGroup)
    {
        ActionManager.AddAction(actionGroup);
    }
}
